<html><head><meta charset="utf-8"><title>26 惊叹面试官：由浅入深手写队列 -慕课专栏</title>
			<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
			<meta name="renderer" content="webkit">
			<meta property="qc:admins" content="77103107776157736375">
			<meta property="wb:webmaster" content="c4f857219bfae3cb">
			<meta http-equiv="Access-Control-Allow-Origin" content="*">
			<meta http-equiv="Cache-Control" content="no-transform ">
			<meta http-equiv="Cache-Control" content="no-siteapp">
			<link rel="apple-touch-icon" sizes="76x76" href="https://www.imooc.com/static/img/common/touch-icon-ipad.png">
			<link rel="apple-touch-icon" sizes="120x120" href="https://www.imooc.com/static/img/common/touch-icon-iphone-retina.png">
			<link rel="apple-touch-icon" sizes="152x152" href="https://www.imooc.com/static/img/common/touch-icon-ipad-retina.png">
			<link href="https://moco.imooc.com/captcha/style/captcha.min.css" rel="stylesheet">
			<link rel="stylesheet" href="https://www.imooc.com/static/moco/v1.0/dist/css/moco.min.css?t=201907021539" type="text/css">
			<link rel="stylesheet" href="https://www.imooc.com/static/lib/swiper/swiper-3.4.2.min.css?t=201907021539">
			<link rel="stylesheet" href="https://static.mukewang.com/static/css/??base.css,common/common-less.css?t=2.5,column/zhuanlanChapter-less.css?t=2.5,course/inc/course_tipoff-less.css?t=2.5?v=201907051055" type="text/css">
			<link charset="utf-8" rel="stylesheet" href="https://www.imooc.com/static/lib/ueditor/themes/imooc/css/ueditor.css?v=201907021539"><link rel="stylesheet" href="https://www.imooc.com/static/lib/baiduShare/api/css/share_style0_16.css?v=6aba13f0.css"></head>
			<body><div id="main">


<div class="main-con hide-menu">
    <!-- 左侧菜单 & 索引 -->
    
    <div class="right-content" style="padding-left: 0px;">
        <div class="container clearfix" id="top" style="width: 1134px; display: block;">
            
            
            <div class="center_con js-center_con l" style="width: 1134px;">
                <div class="article-con">
                                            <!-- 买过的阅读 -->
                        

                    
                    <div class="art-title" style="margin-top: 0px;">
                        26 惊叹面试官：由浅入深手写队列 
                    </div>
                    <div class="art-info clearfix">
                        
                        <span class="l">
                            更新时间：2019-11-04 10:16:59
                        </span>
                    </div>
                    <div class="art-top">
                                                <img src="https://img.mukewang.com/5db7a3440001f1af06400359.jpg" alt="">
                                                                        <div class="famous-word-box">
                            <img src="https://www.imooc.com/static/img/column/bg-l.png" alt="" class="bg1 bg">
                            <img src="https://www.imooc.com/static/img/column/bg-r.png" alt="" class="bg2 bg">
                            <div class="famous-word">人生的价值，并不是用时间，而是用深度去衡量的。<p class="author">——列夫·托尔斯泰</p></div>
                        </div>
                                            </div>
                    <div class="art-content js-lookimg">
                        <div id="article_content">
                            <div class="cl-preview-section"><h2 id="引导语" style="font-size: 30px;">引导语</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">现在不少大厂面试的时候会要求手写代码，我曾经看过一个大厂面试时，要求在线写代码，题目就是：在不使用 Java 现有队列 API 的情况下，手写出一个队列的实现出来，队列的数据结构，入队和出队方式都自己定义。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这题其实考察的有几个点：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">考察你对队列的内部结构熟不熟悉；</li>
<li style="font-size: 20px; line-height: 38px;">考察你定义 API 的功底；</li>
<li style="font-size: 20px; line-height: 38px;">考察写代码的基本功，代码风格。</li>
</ol>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">本章就和大家一起，结合以上几点，手写一个队列出来，一起来熟悉一下思路和过程，完整队列代码见：demo.four.DIYQueue 和 demo.four.DIYQueueDemo</p>
</div><div class="cl-preview-section"><h2 id="接口定义" style="font-size: 30px;">1 接口定义</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在实现队列之前，我们首先需要定义出队列的接口，就是我们常说的 API，API 是我们队列的门面，定义时主要原则就是简单和好用。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们这次实现的队列只定义放数据和拿数据两个功能，接口定义如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token comment">/**
* 定义队列的接口，定义泛型，可以让使用者放任意类型到队列中去
* author  wenhe
* date 2019/9/1
*/</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">Queue</span><span class="token operator">&lt;</span>T<span class="token operator">&gt;</span> <span class="token punctuation">{</span>

  <span class="token comment">/**
   * 放数据
   * @param item 入参
   * @return true 成功、false 失败
   */</span>
  <span class="token keyword">boolean</span> <span class="token function">put</span><span class="token punctuation">(</span>T item<span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">/**
   * 拿数据，返回一个泛型值
   * @return
   */</span>
  T <span class="token function">take</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 队列中元素的基本结构</span>
  <span class="token keyword">class</span> <span class="token class-name">Node</span><span class="token operator">&lt;</span>T<span class="token operator">&gt;</span> <span class="token punctuation">{</span>
    <span class="token comment">// 数据本身</span>
    T item<span class="token punctuation">;</span>
    <span class="token comment">// 下一个元素</span>
    Node<span class="token operator">&lt;</span>T<span class="token operator">&gt;</span> next<span class="token punctuation">;</span>

    <span class="token comment">// 构造器</span>
    <span class="token keyword">public</span> <span class="token function">Node</span><span class="token punctuation">(</span>T item<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>item <span class="token operator">=</span> item<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">有几点我们说明下：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">
<p style="font-size: 20px; line-height: 38px;">定义接口时，一定要写注释，接口的注释，方法的注释等等，这样别人看我们的接口时，会轻松很多‘；</p>
</li>
<li style="font-size: 20px; line-height: 38px;">
<p style="font-size: 20px; line-height: 38px;">定义接口时，要求命名简洁明了，最好让别人一看见命名就知道这个接口是干啥的，比如我们命名为 Queue，别人一看就清楚这个接口是和队列相关的；</p>
</li>
<li style="font-size: 20px; line-height: 38px;">
<p style="font-size: 20px; line-height: 38px;">用好泛型，因为我们不清楚放进队列中的到底都是那些值，所以我们使用了泛型 T，表示可以在队列中放任何值；</p>
</li>
<li style="font-size: 20px; line-height: 38px;">
<p style="font-size: 20px; line-height: 38px;">接口里面无需给方法写上 public 方法，因为接口中的方法默认都是 public 的，你写上编译器也会置灰，如下图：<br>
<img class="" src="https://img.mukewang.com/5db14faa0001928904140484.png" data-original="//img.mukewang.com/5db14faa0001928904140484.png" alt="图片描述"></p>
</li>
<li style="font-size: 20px; line-height: 38px;">
<p style="font-size: 20px; line-height: 38px;">我们在接口中定义了基础的元素 Node，这样队列子类如果想用的话，可以直接使用，增加了复用的可能性。</p>
</li>
</ol>
</div><div class="cl-preview-section"><h2 id="队列子类实现" style="font-size: 30px;">2 队列子类实现</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">接着我们就要开始写子类实现了，我们准备写个最常用的链表数据结构的队列。</p>
</div><div class="cl-preview-section"><h3 id="数据结构">2.1 数据结构</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">底层数据结构我们采用链表，一说到链表，大家应该马上就会想到三个关键要素：链表头、链表尾和链表元素，我们也实现了，代码如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token comment">/**
 * 队列头
 */</span>
<span class="token keyword">private</span> <span class="token keyword">volatile</span> Node<span class="token operator">&lt;</span>T<span class="token operator">&gt;</span> head<span class="token punctuation">;</span>

<span class="token comment">/**
 * 队列尾
 */</span>
<span class="token keyword">private</span> <span class="token keyword">volatile</span> Node<span class="token operator">&lt;</span>T<span class="token operator">&gt;</span> tail<span class="token punctuation">;</span>

<span class="token comment">/**
 * 自定义队列元素
 */</span>
<span class="token keyword">class</span> <span class="token class-name">DIYNode</span> <span class="token keyword">extends</span> <span class="token class-name">Node</span><span class="token operator">&lt;</span>T<span class="token operator">&gt;</span><span class="token punctuation">{</span>
  <span class="token keyword">public</span> <span class="token function">DIYNode</span><span class="token punctuation">(</span>T item<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">super</span><span class="token punctuation">(</span>item<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">除了这些元素之外，我们还有队列容器的容量大小、队列目前的使用大小、放数据锁、拿数据锁等等，代码如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token comment">/**
 * 队列的大小，使用 AtomicInteger 来保证其线程安全
 */</span>
<span class="token keyword">private</span> AtomicInteger size <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">AtomicInteger</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">/**
 * 容量
 */</span>
<span class="token keyword">private</span> <span class="token keyword">final</span> Integer capacity<span class="token punctuation">;</span>

<span class="token comment">/**
 * 放数据锁
 */</span>
<span class="token keyword">private</span> ReentrantLock putLock <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ReentrantLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">/**
 * 拿数据锁
 */</span>
<span class="token keyword">private</span> ReentrantLock takeLock <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ReentrantLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><h3 id="初始化">2.2 初始化</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们提供了使用默认容量（Integer 的最大值）和指定容量两种方式，代码如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token comment">/**
 * 无参数构造器，默认最大容量是 Integer.MAX_VALUE
 */</span>
<span class="token keyword">public</span> <span class="token function">DIYQueue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  capacity <span class="token operator">=</span> Integer<span class="token punctuation">.</span>MAX_VALUE<span class="token punctuation">;</span>
  head <span class="token operator">=</span> tail <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DIYNode</span><span class="token punctuation">(</span>null<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment">/**
 * 有参数构造器，可以设定容量的大小
 * @param capacity
 */</span>
<span class="token keyword">public</span> <span class="token function">DIYQueue</span><span class="token punctuation">(</span>Integer capacity<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 进行边界的校验</span>
  <span class="token keyword">if</span><span class="token punctuation">(</span>null <span class="token operator">==</span> capacity <span class="token operator">||</span> capacity <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalArgumentException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>capacity <span class="token operator">=</span> capacity<span class="token punctuation">;</span>
  head <span class="token operator">=</span> tail <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DIYNode</span><span class="token punctuation">(</span>null<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><h3 id="put-方法的实现">2.3 put 方法的实现</h3>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">put</span><span class="token punctuation">(</span>T item<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 禁止空数据</span>
  <span class="token keyword">if</span><span class="token punctuation">(</span>null <span class="token operator">==</span> item<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">try</span><span class="token punctuation">{</span>
    <span class="token comment">// 尝试加锁，500 毫秒未获得锁直接被打断</span>
    <span class="token keyword">boolean</span> lockSuccess <span class="token operator">=</span> putLock<span class="token punctuation">.</span><span class="token function">tryLock</span><span class="token punctuation">(</span><span class="token number">300</span><span class="token punctuation">,</span> TimeUnit<span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">if</span><span class="token punctuation">(</span><span class="token operator">!</span>lockSuccess<span class="token punctuation">)</span><span class="token punctuation">{</span>
	  <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
	<span class="token punctuation">}</span>
    <span class="token comment">// 校验队列大小</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>size<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> capacity<span class="token punctuation">)</span><span class="token punctuation">{</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"queue is full"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token comment">// 追加到队尾</span>
    tail <span class="token operator">=</span> tail<span class="token punctuation">.</span>next <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DIYNode</span><span class="token punctuation">(</span>item<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 计数</span>
    size<span class="token punctuation">.</span><span class="token function">incrementAndGet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span><span class="token punctuation">{</span>
    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"tryLock 500 timeOut"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span> <span class="token keyword">catch</span><span class="token punctuation">(</span>Exception e<span class="token punctuation">)</span><span class="token punctuation">{</span>
    log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"put error"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
    putLock<span class="token punctuation">.</span><span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">put 方法的实现有几点我们需要注意的是：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">注意 try catch finally 的节奏，catch 可以捕捉多种类型的异常，我们这里就捕捉了超时异常和未知异常，在 finally 里面一定记得要释放锁，不然锁不会自动释放的，这个一定不能用错，体现了我们代码的准确性；</li>
<li style="font-size: 20px; line-height: 38px;">必要的逻辑检查还是需要的，比如入参是否为空的空指针检查，队列是否满的临界检查，这些检查代码可以体现出我们逻辑的严密性；</li>
<li style="font-size: 20px; line-height: 38px;">在代码的关键地方加上日志和注释，这点也是非常重要的，我们不希望关键逻辑代码注释和日志都没有，不利于阅读代码和排查问题；</li>
<li style="font-size: 20px; line-height: 38px;">注意线程安全，此处实现我们除了加锁之外，对于容量的大小（size）我们选择线程安全的计数类：AtomicInteger，来保证了线程安全；</li>
<li style="font-size: 20px; line-height: 38px;">加锁的时候，我们最好不要使用永远阻塞的方法，我们一定要用带有超时时间的阻塞方法，此处我们设置的超时时间是 300 毫秒，也就是说如果 300 毫秒内还没有获得锁，put 方法直接返回 false，当然时间大小你可以根据情况进行设置；</li>
<li style="font-size: 20px; line-height: 38px;">根据不同的情况设置不同的返回值，put 方法返回的是 false，在发生异常时，我们可以选择返回 false，或者直接抛出异常；</li>
<li style="font-size: 20px; line-height: 38px;">put 数据时追加到队尾的，所以我们只需要把新数据转化成 DIYNode，放到队列的尾部即可。</li>
</ol>
</div><div class="cl-preview-section"><h3 id="take-方法的实现">2.4 take 方法的实现</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">take 方法和 put 方法的实现非常类似，只不过 take 是从头部拿取数据，代码实现如下：</p>
</div><div class="cl-preview-section"><pre class=" language-java"><code class="prism  language-java"><span class="token keyword">public</span> T <span class="token function">take</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 队列是空的，返回 null</span>
  <span class="token keyword">if</span><span class="token punctuation">(</span>size<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">return</span> null<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">try</span> <span class="token punctuation">{</span>
    <span class="token comment">// 拿数据我们设置的超时时间更短</span>
    <span class="token keyword">boolean</span> lockSuccess <span class="token operator">=</span> takeLock<span class="token punctuation">.</span><span class="token function">tryLock</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span>TimeUnit<span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">if</span><span class="token punctuation">(</span><span class="token operator">!</span>lockSuccess<span class="token punctuation">)</span><span class="token punctuation">{</span>
	    <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">(</span><span class="token string">"加锁失败"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">}</span>
    <span class="token comment">// 把头结点的下一个元素拿出来</span>
    Node expectHead <span class="token operator">=</span> head<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
    <span class="token comment">// 把头结点的值拿出来</span>
    T result <span class="token operator">=</span> head<span class="token punctuation">.</span>item<span class="token punctuation">;</span>
    <span class="token comment">// 把头结点的值置为 null，帮助 gc</span>
    head<span class="token punctuation">.</span>item <span class="token operator">=</span> null<span class="token punctuation">;</span>
    <span class="token comment">// 重新设置头结点的值</span>
    head <span class="token operator">=</span> <span class="token punctuation">(</span>DIYNode<span class="token punctuation">)</span> expectHead<span class="token punctuation">;</span>
    size<span class="token punctuation">.</span><span class="token function">decrementAndGet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 返回头结点的值</span>
    <span class="token keyword">return</span> result<span class="token punctuation">;</span>
  <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">" tryLock 200 timeOut"</span><span class="token punctuation">,</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">" take error "</span><span class="token punctuation">,</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token keyword">finally</span> <span class="token punctuation">{</span>
      takeLock<span class="token punctuation">.</span><span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 <span class="token punctuation">}</span>
  <span class="token keyword">return</span> null<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">通过以上几步，我们的队列已经写完了，完整代码见：demo.four.DIYQueue。</p>
</div><div class="cl-preview-section"><h2 id="测试" style="font-size: 30px;">3 测试</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">API 写好了，接下来我们要针对 API 写一些场景测试和单元测试，我们先写个场景测试，看看 API 能否跑通，代码如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token annotation punctuation">@Slf4j</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DIYQueueDemo</span> <span class="token punctuation">{</span>
	<span class="token comment">// 我们需要测试的队列</span>
  <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">static</span> Queue<span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> queue <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DIYQueue</span><span class="token operator">&lt;</span><span class="token operator">&gt;</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token comment">// 生产者</span>
  <span class="token keyword">class</span> <span class="token class-name">Product</span> <span class="token keyword">implements</span> <span class="token class-name">Runnable</span><span class="token punctuation">{</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> String message<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token function">Product</span><span class="token punctuation">(</span>String message<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>message <span class="token operator">=</span> message<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">try</span> <span class="token punctuation">{</span>
        <span class="token keyword">boolean</span> success <span class="token operator">=</span> queue<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>message<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>success<span class="token punctuation">)</span> <span class="token punctuation">{</span>
          log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"put {} success"</span><span class="token punctuation">,</span> message<span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token keyword">return</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"put {} fail"</span><span class="token punctuation">,</span> message<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"put {} fail"</span><span class="token punctuation">,</span> message<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
	<span class="token comment">// 消费者</span>
  <span class="token keyword">class</span> <span class="token class-name">Consumer</span> <span class="token keyword">implements</span> <span class="token class-name">Runnable</span><span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">try</span> <span class="token punctuation">{</span>
        String message <span class="token operator">=</span> <span class="token punctuation">(</span>String<span class="token punctuation">)</span> queue<span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"consumer message :{}"</span><span class="token punctuation">,</span>message<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"consumer message fail"</span><span class="token punctuation">,</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
	<span class="token comment">// 场景测试</span>
  <span class="token annotation punctuation">@Test</span>
  <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testDIYQueue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> InterruptedException <span class="token punctuation">{</span>
    ThreadPoolExecutor executor <span class="token operator">=</span>
        <span class="token keyword">new</span> <span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span><span class="token number">10</span><span class="token punctuation">,</span><span class="token number">0</span><span class="token punctuation">,</span>TimeUnit<span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span>
                               <span class="token keyword">new</span> <span class="token class-name">LinkedBlockingQueue</span><span class="token operator">&lt;</span><span class="token operator">&gt;</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">1000</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 是偶数的话，就提交一个生产者，奇数的话提交一个消费者</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span>i <span class="token operator">%</span> <span class="token number">2</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
          executor<span class="token punctuation">.</span><span class="token function">submit</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Product</span><span class="token punctuation">(</span>i<span class="token operator">+</span><span class="token string">""</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token keyword">continue</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        executor<span class="token punctuation">.</span><span class="token function">submit</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Consumer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    Thread<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">10000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">代码测试的场景比较简单，从 0 开始循环到 1000，如果是偶数，就让生产者去生产数据，并放到队列中，如果是奇数，就让消费者去队列中拿数据出来进行消费，运行之后的结果如下：</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><img class="" src="https://img.mukewang.com/5db14fc70001617f08660711.png" data-original="//img.mukewang.com/5db14fc70001617f08660711.png" alt="图片描述"><br>
从显示的结果来看，咱们写的 DIYQueue 没有太大的问题，当然如果想大规模的使用，还需要详细的单元测试和性能测试。</p>
</div><div class="cl-preview-section"><h2 id="总结" style="font-size: 30px;">4 总结</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">通过本章的学习，不知道你有没有一种队列很简单的感觉，其实队列本身就很简单，没有想象的那么复杂。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">只要我们懂得了队列的基本原理，清楚几种常用的数据结构，手写队列问题其实并不大，你也赶紧来试一试吧。</p>
</div>}
                        </div>
                    </div>
                                            <!-- 买过的阅读 -->
                        <div class="art-next-prev clearfix">
                                                                                                <!-- 已买且开放 或者可以试读 -->
                                    <a href="/read/47/article/867">
                                                                    <div class="prev l clearfix">
                                        <div class="icon l">
                                            <i class="imv2-arrow3_l"></i>
                                        </div>
                                        <p>
                                            25 整体设计：队列设计思想、工作中使用场景
                                        </p>
                                    </div>
                                </a>
                                                                                                                            <!-- 已买且开放 或者可以试读 -->
                                    <a href="/read/47/article/869">
                                                                    <div class="next r clearfix">
                                        <p>
                                            27 Thread 源码解析  
                                        </p>
                                        <div class="icon r">
                                            <i class="imv2-arrow3_r"></i>
                                        </div>

                                    </div>
                                </a>
                                                    </div>
                                    </div>
                <div class="comments-con js-comments-con" id="coments_con">
                </div>

                
            </div>
            
            
            

        </div>
    </div>
</div>

<div class="modal modal-jiaQun-new hide" id="modal-jiaQun">
    <div class="inner" style="">
        <div class="modal-close js-close-jiaQun">
            <i class="imv2-close"></i>
        </div>
        <div class="content">
            <img src="https://img.mukewang.com/5d634d40000119e505400602.jpg">
            <div class="right-info">
                <div class="title">
                    扫码加入慕课Java核心用户群
                </div>
                <div class="desc">
                                            <p class="mb6">验证信息：<span id="joincode">1909271435058473</span><span class="copy js-copy-joincode">复制</span></p>
                                        <p class="mb6">QQ讨论群号：906691736</p>
                                            <p>QQ群URL：<a href="https://jq.qq.com/?_wv=1027&amp;k=55RtSbJ" target="_blank">点击访问</a></p>
                                    </div>
            </div>
            <p class="tip">若遇到搜索不到QQ群或加群失败，请联系客服邮箱:kf@imooc.com</p>
        </div>
    </div>
</div>
 
<!-- 专栏介绍页专栏评价 -->

<!-- 专栏介绍页底部三条评价 -->

<!-- 专栏阅读页弹层目录和介绍页页面目录 -->

<!-- 专栏阅读页发布回复 -->

<!-- 专栏阅读页发布评论 -->

<!-- 专栏阅读页底部评论 -->

<!-- 专栏阅读 单个 评论 -->

<!-- 新增回复和展开三条以外回复 -->

<!-- 立即订阅的弹窗 -->












</div></body></html>